package top.ajunnihao.core.web.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import top.ajunnihao.core.entity.User;
import top.ajunnihao.core.entity.UserAbility;
import top.ajunnihao.core.service.UserAbilityService;
import top.ajunnihao.core.service.UserService;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.net.URLDecoder;

/**
 * TODO 自动登录拦截器
 *
 * @author AJun
 * @version 1.0.0
 * @date 2020/6/1
 */
public class AutoLoginInterceptor implements HandlerInterceptor {

    private static final String USER = "USER";
    private static final String USER_ABILITY = "USER_ABILITY";
    private static final String LOGIN_USERNAME = "loginUsername";
    private static final String LOGIN_USER_PWD = "loginUserPwd";

    @Autowired
    private UserService userService;
    @Autowired
    private UserAbilityService userAbilityService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 实现自动登录
        String loginCookieUsername = "";
        String loginCookiePwd = "";
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (LOGIN_USERNAME.equals(cookie.getName())) {
                    // URL 解码，防止中文用户名乱码
                    loginCookieUsername = URLDecoder.decode(cookie.getValue(), "UTF-8");
                } else if (LOGIN_USER_PWD.equals(cookie.getName())) {
                    loginCookiePwd = cookie.getValue();
                }
            }
            if (!"".equals(loginCookieUsername) && !"".equals(loginCookiePwd)) {
                // 如果不为空，则校验用户密码，存入 session
                User u = userService.findUserByName(loginCookieUsername);
                if (loginCookiePwd.equals(u.getPassword())) {
                    // 根据用户 id 查询用户权利，存入 session
                    UserAbility userAbility = userAbilityService.findUserAbilityByUserId(u.getId());
                    HttpSession session = request.getSession();
                    session.setAttribute(USER, u);
                    session.setAttribute(USER_ABILITY, userAbility);
                }
            }
        }
        return true;
    }

}
